package com.jjiang.bbmall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.jjiang.common.exception.BizCodeEnumerate;
import com.jjiang.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class SentinelGatewayConfig {
    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            // 如果网关限流的请求，则返回此结果
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnumerate.TOO_MANY_REQUEST_EXCEPTION.getCode(), BizCodeEnumerate.TOO_MANY_REQUEST_EXCEPTION.getMsg());
                String string = JSON.toJSONString(error);
                return ServerResponse.ok().body(Mono.just(string), String.class);
            }
        });
    }
}
